package com.wfbi.security.chapter3;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.PrintWriter;

/**
 * @author wfbi
 * @version 1.0
 * @date 2021/12/27 2:13 PM
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 采用不加密策略
     *
     * @author: wfbi
     * @date: 2021/12/27 2:18 PM
     * @return: org.springframework.security.crypto.password.PasswordEncoder
     **/
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 内存中定义用户
     *
     * @param auth:
     * @author: wfbi
     * @date: 2021/12/27 2:17 PM
     * @return: void
     **/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("wfbi")
                .password("wfbi")
                .roles("admin");
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        // 配置忽略掉的 URL 地址，一般对于静态文件
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
    }

    /**
     * 权限配置
     *
     * @param http:
     * @author: wfbi
     * @date: 2021/12/27 2:23 PM
     * @return: void
     **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                // 表单相关配置
                .formLogin()
                // 设置登录页面
                .loginPage("/login.html")
                // 设置登录提交路径，默认和loginPage同值
                .loginProcessingUrl("/doLogin")
                // 设置登录表单用户名关键变量
                .usernameParameter("name")
                // 设置登录表单用户密码关键变量
                .passwordParameter("passwd")
                // 成功处理方法。successHandler 方法的参数是一个 AuthenticationSuccessHandler 对象，要实现的方法是 onAuthenticationSuccess。
                // HttpServletRequest 可以做服务端跳转或返回json; HttpServletResponse 可以做客户端跳转或返回json;Authentication 参数则保存了登录成功的用户信息
                .successHandler((req, resp, authentication) -> {
                    Object principal = authentication.getPrincipal();
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(principal));
                    out.flush();
                    out.close();
                })
                // 失败处理方法. e是一个登录失败Exception，封装json返回异常信息
                .failureHandler((req, resp, e) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(e.getMessage());
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                // 注销登录相关配置
                .logout()
                // 默认注销的 URL 是 /logout，是一个 GET 请求，我们可以通过 logoutUrl 方法来修改默认的注销 URL
                .logoutUrl("/logout")
                // 注销成功处理方法.
                .logoutSuccessHandler((req, resp, authentication) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("注销成功");
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .csrf().disable().exceptionHandling()
                .authenticationEntryPoint((req, resp, authException) -> {
                            resp.setContentType("application/json;charset=utf-8");
                            PrintWriter out = resp.getWriter();
                            out.write("尚未登录，请先登录");
                            out.flush();
                            out.close();
                        }
                );
    }
}
